#include <iostream>
#include <string>
#include <functional>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
#include <pthread.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <memory>

#include "InetAddr.hpp"
#include "Log.hpp"
#include "Socket.hpp"

// 创建服务器时，只需要传 port 和 任务函数
// 只提供多线程来处理服务，并不涉及服务的具体实现
// 实现松耦合

using namespace socket_ns;
using http_t = std::function<std::string(std::string request)>;

class TcpServer;

class ThreadData
{
public:
    ThreadData(socket_sptr fd, InetAddr addr, TcpServer *s)
        : sockfd(fd), clientaddr(addr), self(s)
    {
    }

public:
    socket_sptr sockfd;
    InetAddr clientaddr;
    TcpServer *self;
};

class TcpServer
{
public:
    TcpServer(int port, http_t service)
        : _localaddr("0", port),
          _listensock(std::make_unique<TcpSocket>()),
          _http_service(service),
          _isrunning(false)
    {
        _listensock->BuildListenSocket(_localaddr);
    }

    // 由多线程处理任务
    static void *HandlerSock(void *args)
    {
        pthread_detach(pthread_self());

        ThreadData *td=static_cast<ThreadData*>(args);
        std::string request,response;

        // 读取请求
        ssize_t n=td->sockfd->Recv(&request);
        if(n>0)
        {
            response=td->self->_http_service(request);// 处理请求
            td->sockfd->Send(response);//发送应答

        }

        td->sockfd->Close();
        delete td;
        return nullptr;
    }

    void Loop()
    {
        _isrunning = true;
        while (_isrunning)
        {
            InetAddr peeraddr;
            socket_sptr normalsock = _listensock->Accepter(&peeraddr); // 接收连接
            if (normalsock == nullptr)
                continue;

            // 多线程
            pthread_t pid;
            ThreadData *td = new ThreadData(normalsock,peeraddr,this);

            pthread_create(&pid, nullptr, HandlerSock, td);
        }
        _isrunning = true;
    }
    ~TcpServer()
    {
    }

private:
    InetAddr _localaddr;
    std::unique_ptr<Socket> _listensock;
    bool _isrunning;

    http_t _http_service; // 任务
};
